import { Input } from 'antd'
import PubSub from 'pubsub-js'

import React, { Component } from 'react'
//import axios from 'axios'
export default class Header extends Component {
    state = {
        loading: false
    }
    onSearch = async value => {
        if (!value) {
            return
        }
        this.setState({ loading: true })
        PubSub.publish("ready", { loading: true, isFirst: false })

        // axios.get(`https://api.github.com/search/users?q=${value}`)
        //     .then(response => {
        //         this.setState({ loading: false })
        //         console.log(response.data)
        //         PubSub.publish("ready", { userPage: response.data, loading: false })
        //     }, error => {
        //         this.setState({ loading: false })
        //         PubSub.publish("ready", { loading: false, err: error.message })
        //         console.log(error)
        //     })

        //未优化
        // fetch(`https://api.github.com/search/users?q=${value}`).then(response => {
        //     console.log("联系服务器成功", response)
        //     return response.json()
        // }, error => {
        //     console.log("联系服务器失败", error)
        //     //结束promise链式调用
        //     return new Promise(() => { })
        // }).then(response => {
        //     console.log("获取数据成功", response)
        // }, error => {
        //     console.log("获取数据失败", error)
        // })

        //优化
        try {
            const response = await fetch(`https://api.github.com/search/users?q=${value}`);
            const data = await response.json();
            this.setState({ loading: false })
            PubSub.publish("ready", { userPage: data, loading: false })
            console.log("请求成功", data)
        } catch (error) {
            this.setState({ loading: false })
            PubSub.publish("ready", { loading: false, err: error.message })
            console.log("请求失败", error)
        }
    }
    render() {
        const { Search } = Input;
        const { loading } = this.state
        return (
            <div style={{ backgroundColor: "white", padding: "15px" }}>
                <h2>搜索 GITHUB 用户</h2>
                <div style={{ display: 'flex' }}>
                    <Search
                        loading={loading}
                        placeholder="请输入用户名"
                        allowClear
                        enterButton
                        size="large"
                        onSearch={this.onSearch}
                    />
                </div>
            </div>
        )
    }
}
